import { useState, useEffect } from 'react';

import { Upload, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import styles from './index.module.sass';

interface UploadFileType {
    ppt: string,
    xlsx: string,
    docx: string,
}

export const fileType: UploadFileType = {
    ppt: '.pptx,.ppt',
    xlsx: '.xlsx,.xls,.csv',
    docx: '.docx,.doc',
}

interface Props {
    /**文件上传地址 */
    url: string

    /**文件上传请求头 */
    headers?: any

    /**用于触发表单值的更新 */
    onChange?: Function

    /**上传的文件数量 */
    uploadNumber?: number

    /**上传的文件类型 */
    uploadFileType?: string | string[]
}

const FileUpload: React.FC<Props> = ({
    url,
    headers,
    onChange,
    uploadNumber = 1,
    uploadFileType = fileType.xlsx,
}) => {
    /**可上传的文件类型 */
    const [accept, setAccept] = useState<string>();

    useEffect(() => {
        if (Array.isArray(uploadFileType)) {
            setAccept(uploadFileType.toString());
        } else if (typeof uploadFileType === 'string') {
            setAccept(uploadFileType);
        } else {
            setAccept(fileType.xlsx);
        }
    }, [uploadFileType])

    function handleChange(file: any) {
        if (file.fileList && Array.isArray(file.fileList)) {
            const uploadDone = file.fileList.every(({ status }: any) => status !== 'uploading');
            if (uploadDone) {
                onChange && onChange(file.fileList);
            }
        }
    };

    return (
        <article className={styles.wrapper}>
            <Upload
                name={'file'}
                accept={accept}
                action={url}
                headers={headers}
                maxCount={uploadNumber}
                onChange={handleChange}
            >
                <Button icon={<UploadOutlined />}>导入</Button>
            </Upload>
            <label>
                {`请选择${uploadFileType}文件导入`}
            </label>
        </article>
    );
}

export default FileUpload
